package com.gujiangbo.defrewlock;

public class ReadLock implements Lock {

    private final ReadWriteLockImpl readWriteLock;

    public ReadLock(ReadWriteLockImpl readWriteLock) {
        this.readWriteLock = readWriteLock;
    }

    @Override
    public void lock() throws InterruptedException {
        //获取mutex对象作为锁，使用同步
        synchronized (readWriteLock.getMutex()) {
            // 若此时有线程正在进行写操作，或者有写线程在等待并且当前的偏向锁写的标识为TRUE，
            // 就会无法获取读锁，只能被挂起
            while (readWriteLock.getWritingWriters() > 0 ||
                    (readWriteLock.getPerferWriter()
                            && readWriteLock.getWaitingWriters() > 0)) {
                readWriteLock.getMutex().wait();
            }
            //成功获取到锁，并且使readingReaders的数量加一
            readWriteLock.incrementReadingReaders();
        }

    }

    @Override
    public void unlock() {
        //使用MUTEX作为锁，并且进行同步
        synchronized (readWriteLock.getMutex()) {
            //释放锁的过程就是使用当前的reading的数量减一
            //将perferWriter设置为TRUE，可以是的writer线程获取更多的执行机会
            //通知唤醒与mutex关联monitor waitset 中的线程
            readWriteLock.decrementReadingReaders();
            readWriteLock.changePerfer(true);
            readWriteLock.getMutex().notifyAll();
        }

    }
}
